﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.ComponentModel;

namespace FHJ.FHPI.PushNotifications.Library.GoogleC2DM
{
    /// <summary>
    /// Authentication provider for Google's services.
    /// </summary>
    public sealed class AuthProvider
    {
        #region Singleton stuff
        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        private AuthProvider()
        {
            // Nothing to do here at the moment...
        }

        /// <summary>
        /// The AuthProvider singleton instance.
        /// </summary>
        private static AuthProvider instance;
        /// <summary>
        /// The SyncRoot for the AuthProvider instance.
        /// </summary>
        private static Object instanceSyncRoot = new Object();

        /// <summary>
        /// Gets the AuthProvider instance.
        /// </summary>
        public static AuthProvider Instance
        {
            get
            {
                lock (instanceSyncRoot)
                {
                    if (instance == null)
                        instance = new AuthProvider();

                    return instance;
                }
            }
        }
        #endregion

        /// <summary>
        /// The Username of the account which is used to send messages.
        /// </summary>
        private String UserName
        {
            get;
            set;
        }

        /// <summary>
        /// The Password of the account which is used to send messages.
        /// </summary>
        private String PassWord
        {
            get;
            set;
        }

        private String authToken = null;
        private DateTime? authTokenLastRefresh = null;
        private Object authTokenSyncRoot = new Object();
        
        /// <summary>
        /// Gets the authentication token.
        /// </summary>
        /// <param name="isTokenValid">Indicates whether the token is valid.</param>
        /// <param name="tokenValue">If <paramref name="isTokenValid"/> is true, contains the authentication token.</param>
        public void GetAuthToken(out Boolean isTokenValid, out String tokenValue)
        {
            try
            {
                lock (authTokenSyncRoot)
                {
                    if (authToken == null)
                    {
                        isTokenValid = false;
                        tokenValue = null;
                    }
                    else
                    {
                        isTokenValid = true;
                        tokenValue = authToken;
                    }
                }
            }
            catch (Exception)
            {                
                throw;
            }
        }

        /// <summary>
        /// Retrieves the ClientLogin authentication token.
        /// </summary>
        private void InitializeClientLoginToken()
        {
            try
            {
                lock (authTokenSyncRoot)
                {
                    String tokenValue = RequestHandler.DoAuthTokenRequest(UserName, PassWord);

                    authToken = tokenValue;
                    authTokenLastRefresh = DateTime.Now;
                }
            }
            catch (Exception)
            {
                lock (authTokenSyncRoot)
                {
                    authToken = null;
                }

                throw;

                // ToDo: Log
            }
        }

        /// <summary>
        /// Can be invoked by other code parts within this library to signal that the authentication token has become invalid.
        /// </summary>
        public void RefreshAuthToken()
        {
            try
            {
                // Refresh the auth token in a background thread...
                Task refreshTask = new Task(delegate()
                    {
                        InitializeClientLoginToken();
                    });

                refreshTask.Start();
            }
            catch (Exception)
            {                
                throw;
            }
        }

        /// <summary>
        /// Initializes the AuthProvider with the necessary data.
        /// </summary>
        /// <param name="userName">The username of the google account which is used to send messages.</param>
        /// <param name="passWord">The password for the account.</param>
        /// <param name="tokenRefreshInterval">Interval in which the token will be refreshed. (in seconds)</param>
        public void Initialize(String userName, String passWord, Int32 tokenRefreshInterval)
        {
            try
            {
                if (String.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (String.IsNullOrEmpty(passWord))
                    throw new ArgumentNullException("passWord");

                UserName = userName;
                PassWord = passWord;

                InitializeClientLoginToken();
                                
                // ToDo: Implement authentication token refresh logic...
            }
            catch (Exception)
            {                
                throw;
            }
        }
    }
}
